package sisi.invoices;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Button;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Hlayout;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.MyEmf;
import sisi.broker.Broker;
import sisi.broker.BrokerController;
import sisi.corporation.Corporation;
import sisi.corporation.CorporationController;
import sisi.suppliers.Supplier;
import sisi.suppliers.SupplierController;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;

public class CustSuppCardWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// window
	private Window finestraDettaglio, windowCustSuppCard;
	private Listbox boxDetail, boxSupplier;
	private Listbox boxBoatName, boxBroker, boxCorporation, boxCustUSD, boxCustEUR;

	protected Map<String, Object> args;
	// edit
	//
	private Textbox tbSearchBoatName, tbSearchSupplier, tbSearchBroker, tbSearchCorporation;
	private Bandbox bbBoatName, bbBroker, bbCorporation, bbSupplier;
	private Intbox idBoatName, idBroker, idCorporation, ibSupplier;
	
	private boolean customersCard = true;
	
	private Label lblCustSupp;
	private Hlayout hlSupplier, hlCustomer;
	private Row rowCorpCustomer, rowBroker, rowCorporation;
	private Textbox tbCorporationCustomer;
	private Datebox dbBeginDate, dbEndDate, dbDateReport;
	private Doublebox dbTotalInvoiced, dbPaidInvoices, dbExpiredInvoices, dbGrandTotalDue;
	private Doublebox dbTotalInvoicedE, dbPaidInvoicesE, dbExpiredInvoicesE, dbGrandTotalDueE;
	private boolean clicked = false;
	private Button btnPreviewStatement;
	private Listheader lhUSDCustName, lhEURCustName;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void onCreate$windowCustSuppCard(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		customersCard = (Boolean) args.get("customers");
		
		if (customersCard){
			windowCustSuppCard.setTitle("Customer's Card");
			hlSupplier.setVisible(false);
			lblCustSupp.setLeft("Customer:");
			lhUSDCustName.setLabel("Customer Name");
			lhEURCustName.setLabel("Customer Name");
		} else {
			windowCustSuppCard.setTitle("Supplier's Card");
			hlCustomer.setVisible(false);
			rowBroker.setVisible(false);
			rowCorpCustomer.setVisible(false);
			rowCorporation.setVisible(false);
			lblCustSupp.setLeft("Supplier:");
			lhUSDCustName.setLabel("Supplier Name");
			lhEURCustName.setLabel("Supplier Name");
		}
		
		Calendar cBeginDate = Calendar.getInstance();
		Calendar cEndDate = Calendar.getInstance();
		
		cBeginDate.setTime(new Date());
		cBeginDate.set(Calendar.DAY_OF_MONTH, 1);
		
		cEndDate.setTime(cBeginDate.getTime());
		cEndDate.add(Calendar.MONTH, 1);
		cEndDate.set(Calendar.DAY_OF_MONTH, 1);
		cEndDate.add(Calendar.DAY_OF_MONTH, -1); // ultimo giorno del mese

		dbBeginDate.setValue(cBeginDate.getTime());
		dbEndDate.setValue(cEndDate.getTime());
		
		
		// CUSTOMER
		ListModelList listModelListYachts = new ListModelList();
		listModelListYachts.addAll(new AnayachtController()
				.getAnayachtList(null));
		boxBoatName.setModel(listModelListYachts);
		boxBoatName.setItemRenderer(new BoatNameRenderer());

		tbSearchBoatName.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoYacht(valore);
			}
		});

		bbBoatName.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoYacht(valore);
			}
		});
		
		
		// BROKER
		ListModelList listModelListBroker = new ListModelList();
		listModelListBroker.addAll(new BrokerController().getBrokerList(null));
		boxBroker.setModel(listModelListBroker);
		boxBroker.setItemRenderer(new BrokerRenderer());

		tbSearchBroker.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoBroker(valore);
			}
		});

		bbBroker.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoBroker(valore);
			}
		});
		
		// CORPORATION
		ListModelList listModelListCorporation = new ListModelList();
		listModelListCorporation.addAll(new CorporationController().getCorporationList(null));
		boxCorporation.setModel(listModelListCorporation);
		boxCorporation.setItemRenderer(new CorporationRenderer());

		tbSearchCorporation.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoCorporation(valore);
			}
		});

		bbCorporation.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoCorporation(valore);
			}
		});		
		

		
		// SUPPLIER
		ListModelList listModelListSupplier = new ListModelList();
		listModelListSupplier.addAll(new SupplierController().getList(null));
		boxSupplier.setModel(listModelListSupplier);
		boxSupplier.setItemRenderer(new SupplierRenderer()); 

		tbSearchSupplier.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoSupplier(valore);
			}
		});
		
		bbSupplier.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent) event;
				String valore = evt.getValue();
				cercoSupplier(valore);
			}
		});
		
		//Component tmp = finestraDettaglio.getFellow("boxDetail");
		//boxDetail = (Listbox) tmp;


	}

	@Override
	public void afterCompose() {	
		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);
	}

	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void cercoSupplier(String nomeSupplier){
		ListModelList listModelListSupplier = new ListModelList();
		listModelListSupplier.addAll(new SupplierController().getList(nomeSupplier));
		boxSupplier.setModel(listModelListSupplier);
		boxSupplier.invalidate();
	}
	
	public void onSelect$boxSupplier(Event event){
		int iSelected = boxSupplier.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oSupplier = boxSupplier.getItemAtIndex(iSelected).getAttribute("rigaSupplier");
		Supplier supplier = (Supplier)oSupplier;
		ibSupplier.setValue(supplier.getSupplid());
		btnPreviewStatement.setDisabled(true);
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void cercoYacht(String nomeYacht){
		ListModelList listModelListYachts = new ListModelList();
		listModelListYachts.addAll(new AnayachtController().getAnayachtList(nomeYacht));
		boxBoatName.setModel(listModelListYachts);
		boxBoatName.invalidate();
		azzeroSelezione(2);
		
	}
	
	public void onSelect$boxBoatName(Event event){
		int iSelected = boxBoatName.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oYacht = boxBoatName.getItemAtIndex(iSelected).getAttribute("rigaBoatName");
		Anayacht yacht = (Anayacht)oYacht;
		idBoatName.setValue(yacht.getId());
		tbCorporationCustomer.setValue(yacht.getCorporation());
		azzeroSelezione(1);
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void cercoBroker(String nomeBroker){
		ListModelList listModelListBroker = new ListModelList();
		listModelListBroker.addAll(new BrokerController().getBrokerList(nomeBroker) );
		boxBroker.setModel(listModelListBroker);
		boxBroker.invalidate();
		azzeroSelezione(2);
	}
	
	public void onSelect$boxBroker(Event event){
		int iSelected = boxBroker.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oBroker = boxBroker.getItemAtIndex(iSelected).getAttribute("rigaBroker");
		Broker yacht = (Broker)oBroker;
		idBroker.setValue(yacht.getId());
		azzeroSelezione(2);
	}	

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void cercoCorporation(String nomeCorporation){
		ListModelList listModelListCorporation = new ListModelList();
		listModelListCorporation.addAll(new CorporationController().getCorporationList(nomeCorporation) );
		boxCorporation.setModel(listModelListCorporation);
		boxCorporation.invalidate();
		azzeroSelezione(3);
	}
	
	public void onSelect$boxCorporation(Event event){
		int iSelected = boxCorporation.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oCorporation = boxCorporation.getItemAtIndex(iSelected).getAttribute("rigaCorporation");
		Corporation corporation = (Corporation)oCorporation;
		idCorporation.setValue(corporation.getCorpid());
		azzeroSelezione(3);
	}	
	
	private void azzeroSelezione(int opzione){
		
		btnPreviewStatement.setDisabled(true);
		
		if (opzione==1){ // customer
			idBroker.setValue(0);
			bbBroker.setValue(null);
			boxBroker.setSelectedIndex(-1);
			tbSearchBroker.setValue(null);
			
			idCorporation.setValue(0);
			bbCorporation.setValue(null);
			boxCorporation.setSelectedIndex(-1);
			tbSearchCorporation.setValue(null);
		} else if (opzione==2){ // broker
			bbBoatName.setValue(null);
			boxBoatName.setSelectedIndex(-1);
			tbCorporationCustomer.setValue(null);
			tbSearchBoatName.setValue(null);
			idBoatName.setValue(0);
			
			
			idCorporation.setValue(0);
			bbCorporation.setValue(null);
			boxCorporation.setSelectedIndex(-1);
			tbSearchCorporation.setValue(null);

		} else if (opzione==3){ // corporation
			
			idBroker.setValue(0);
			bbBroker.setValue(null);
			boxBroker.setSelectedIndex(-1);
			tbSearchBroker.setValue(null);
			
			bbBoatName.setValue(null);
			boxBoatName.setSelectedIndex(-1);
			tbCorporationCustomer.setValue(null);
			tbSearchBoatName.setValue(null);
			idBoatName.setValue(0);
			
		}
		
		
	}
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void onClick$btnSearch(){
		
		if (customersCard){
			// customer's card
			if ( General.integerZeroNull( idBoatName.getValue() ) == 0 && General.integerZeroNull( idBroker.getValue() ) == 0 && General.integerZeroNull( idCorporation.getValue() ) == 0){
				new General().MsgBox("You haven't done any selection, procedure will be terminated!", "NFYS");
				return;
			}
			
			String sqlDeleteTmp = "DELETE FROM customercard";
			
			EntityManager em = new MyEmf().getEntityManager();
			EntityTransaction entr=em.getTransaction();
			entr.begin();
				Query query2 = em.createNativeQuery(sqlDeleteTmp);
				query2.executeUpdate();
			entr.commit();
			String query = "";
			if (idBoatName.getValue() != 0){
				query = "INSERT INTO customercard ( order_, custnuminvoice, curr, totaltaxedvat, invoicedt, duedate, "
						+ " paydt, paidamount, custid, custname) "
			            + " SELECT custinvoice.order_, custinvoice.custnuminvoice, custinvoice.curr, "
			            + " custinvoice.totaltaxedvat, custinvoice.invoicedt, custinvoice.duedate, custinvoice.paydt, "
			            + " custinvoice.paidamount, custinvoice.custid, custinvoice.custname "
			            + " FROM custinvoice "
			            + " WHERE custid =" + idBoatName.getValue() + " and custinvoice.invoicedt>='" + dbBeginDate.getValue() + "' AND custinvoice.invoicedt <= '" + dbEndDate.getValue()+ "' AND custinvoice.type<> 'R' ";
			} else if (idBroker.getValue() != 0){
				query = "INSERT INTO customercard ( order_, custnuminvoice, curr, totaltaxedvat, invoicedt, duedate, "
			            + " paydt, paidamount, custid, custname)"
			            + " SELECT custinvoice.order_, custinvoice.custnuminvoice, custinvoice.curr, " 
			            + " custinvoice.totaltaxedvat, custinvoice.invoicedt, custinvoice.duedate, custinvoice.paydt, " 
			            + " custinvoice.paidamount, custinvoice.custid, custinvoice.custname" 
			            + " FROM (custinvoice INNER JOIN anayacht ON custinvoice.custid = anayacht.id) " 
			            + " Left JOIN broker ON anayacht.brokerid = broker.id" 
			            + " WHERE broker.id =" + idBroker.getValue() + " and custinvoice.invoicedt>= '" + dbBeginDate.getValue() + "' And custinvoice.invoicedt <= '" + dbEndDate.getValue() + "' AND custinvoice.type <> 'R' ";
			} else if (idCorporation.getValue() != 0){
				query = "INSERT INTO customercard ( order_, custnuminvoice, curr, totaltaxedvat, invoicedt, duedate, "
			            + " paydt, paidamount, custid, custname) "
			            + " SELECT custinvoice.order_, custinvoice.custnuminvoice, custinvoice.curr, " 
			            + " custinvoice.totaltaxedvat, custinvoice.invoicedt, custinvoice.duedate, custinvoice.paydt, " 
			            + " custinvoice.paidamount, custinvoice.custid, custinvoice.custname"
			            + " FROM (custinvoice INNER JOIN anayacht ON custinvoice.custid = anayacht.id)" 
			            + " WHERE anayacht.corpid =" + idCorporation.getValue() + " and custinvoice.invoicedt>='" + dbBeginDate.getValue() + "' And custinvoice.invoicedt <= '" + dbEndDate.getValue() + "' AND custinvoice.type <> 'R' ";
			}
				
			        
			entr=em.getTransaction();
			entr.begin();
			query2 = em.createNativeQuery(query);
			query2.executeUpdate();
			entr.commit();
			
			/*
			  order_ integer DEFAULT 0,
			  custnuminvoice integer DEFAULT 0,
			  curr character varying(5),
			  totaltaxedvat double precision DEFAULT 0,
			  invoicedt timestamp without time zone,
			  duedate timestamp without time zone,
			  paydt timestamp without time zone,
			  paidamount double precision DEFAULT 0,
			  custid integer DEFAULT 0,
			  custname character varying(35)
			  */
			// BOX USD
			query = "SELECT order_, custnuminvoice, curr, totaltaxedvat, invoicedt, duedate, paydt, paidamount, custid, custname FROM customercard WHERE curr='USD' ORDER BY order_, custnuminvoice ";
			Query q = em.createNativeQuery(query);
			List risultato = q.getResultList();
			Double totalInvoiced=0.00, paidInvoices=0.00, expiredInvoices=0.00, grandTotalDue=0.00;
			for (Object object : risultato) {
				Object[] oRiga = (Object[])object;
				totalInvoiced += General.doubleZeroNull( (Double)oRiga[3] );
				paidInvoices += General.doubleZeroNull( (Double)oRiga[7]);
				Date payDt = (Date)oRiga[6];
				if (payDt==null){
					expiredInvoices += General.doubleZeroNull( (Double)oRiga[3] );
				}
				
			}
			grandTotalDue = paidInvoices - totalInvoiced;
			dbTotalInvoiced.setValue(totalInvoiced);
			dbPaidInvoices.setValue(paidInvoices);
			dbExpiredInvoices.setValue(expiredInvoices);
			dbGrandTotalDue.setValue(grandTotalDue);
			
			ListModelList listModelListCustUSD = new ListModelList();
			listModelListCustUSD.addAll(risultato);
			boxCustUSD.setModel(listModelListCustUSD);
			boxCustUSD.setItemRenderer(new CustUSDRenderer() );
			
			// BOX EUR
			query = "SELECT order_, custnuminvoice, curr, totaltaxedvat, invoicedt, duedate, paydt, paidamount, custid, custname FROM customercard WHERE curr='EUR' ORDER BY order_, custnuminvoice ";
			q = em.createNativeQuery(query);
			risultato = q.getResultList();
			Double totalInvoicedE=0.00, paidInvoicesE=0.00, expiredInvoicesE=0.00, grandTotalDueE=0.00;
			for (Object object : risultato) {
				Object[] oRiga = (Object[])object;
				totalInvoicedE += General.doubleZeroNull( (Double)oRiga[3] );
				paidInvoicesE += General.doubleZeroNull( (Double)oRiga[7]);
				Date payDt = (Date)oRiga[6];
				if (payDt==null){
					expiredInvoicesE += General.doubleZeroNull( (Double)oRiga[3] );
				}
				
			}
			grandTotalDueE = paidInvoicesE - totalInvoicedE;
			dbTotalInvoicedE.setValue(totalInvoicedE);
			dbPaidInvoicesE.setValue(paidInvoicesE);
			dbExpiredInvoicesE.setValue(expiredInvoicesE);
			dbGrandTotalDueE.setValue(grandTotalDueE);
			
			ListModelList listModelListCustEUR = new ListModelList();
			listModelListCustEUR.addAll(risultato);
			boxCustEUR.setModel(listModelListCustEUR);
			boxCustEUR.setItemRenderer(new CustEURRenderer() );
			
			
			//new General().MsgBox("Fine Procedura!", "NFYS");
			btnPreviewStatement.setDisabled(false);
			
			em.close();
			
		} else {
			// supplier's card
			
			if ( General.integerZeroNull( ibSupplier.getValue() ) == 0 ){
				new General().MsgBox("You haven't done any selection, procedure will be terminated!", "NFYS");
				return;
			}
			
			String sqlDeleteTmp = "DELETE FROM suppliercard";
			
			EntityManager em = new MyEmf().getEntityManager();
			EntityTransaction entr=em.getTransaction();
			entr.begin();
				Query query2 = em.createNativeQuery(sqlDeleteTmp);
				query2.executeUpdate();
			entr.commit();
			String query = "";

			query = "INSERT INTO suppliercard ( order_, suppnuminvoice, curr, totalinvoice, invoicedt, duedate, "
		           +" payddt, paidamount, suppid, suppname) " 
		           +" SELECT suppinvoice.order_, suppinvoice.suppnuminvoice, suppinvoice.curr, "
		           +" suppinvoice.totalinvoice, suppinvoice.invoicedt, suppinvoice.duedate, suppinvoice.payddt, "
		           +" suppinvoice.paidamount, suppinvoice.suppid, suppinvoice.suppname "
		           +" FROM suppinvoice"
		           +" WHERE suppid =" + ibSupplier.getValue() + " and (suppinvoice.invoicedt)>='" + dbBeginDate.getValue() + "' And (suppinvoice.invoicedt) <= '" + dbEndDate.getValue() + "' ";
			
			entr=em.getTransaction();
			entr.begin();
			query2 = em.createNativeQuery(query);
			query2.executeUpdate();
			entr.commit();
			
			/*
			  order_ integer DEFAULT 0,
			  suppnuminvoice character varying(25),
			  curr character varying(5),
			  totalinvoice double precision DEFAULT 0,
			  invoicedt timestamp without time zone,
			  duedate timestamp without time zone,
			  payddt timestamp without time zone,
			  paidamount double precision DEFAULT 0,
			  suppid integer DEFAULT 0,
			  suppname character varying(35)
			 */
			
			// BOX USD
			query = "SELECT order_, suppnuminvoice, curr, totalinvoice, invoicedt, duedate, payddt, paidamount, suppid, suppname FROM suppliercard WHERE curr='USD' ORDER BY order_, suppnuminvoice ";
			Query q = em.createNativeQuery(query);
			List risultato = q.getResultList();
			Double totalInvoiced=0.00, paidInvoices=0.00, expiredInvoices=0.00, grandTotalDue=0.00;
			for (Object object : risultato) {
				Object[] oRiga = (Object[])object;
				totalInvoiced += General.doubleZeroNull( (Double)oRiga[3] );
				paidInvoices += General.doubleZeroNull( (Double)oRiga[7]);
				Date payDt = (Date)oRiga[6];
				if (payDt==null){
					expiredInvoices += General.doubleZeroNull( (Double)oRiga[3] );
				}
				
			}
			grandTotalDue = paidInvoices - totalInvoiced;
			dbTotalInvoiced.setValue(totalInvoiced);
			dbPaidInvoices.setValue(paidInvoices);
			dbExpiredInvoices.setValue(expiredInvoices);
			dbGrandTotalDue.setValue(grandTotalDue);
			
			ListModelList listModelListCustUSD = new ListModelList();
			listModelListCustUSD.addAll(risultato);
			boxCustUSD.setModel(listModelListCustUSD);
			boxCustUSD.setItemRenderer(new CustUSDRenderer() );
			
			// BOX EUR
			query = "SELECT order_, suppnuminvoice, curr, totalinvoice, invoicedt, duedate, payddt, paidamount, suppid, suppname FROM suppliercard WHERE curr='EUR' ORDER BY order_, suppnuminvoice ";
			q = em.createNativeQuery(query);
			risultato = q.getResultList();
			Double totalInvoicedE=0.00, paidInvoicesE=0.00, expiredInvoicesE=0.00, grandTotalDueE=0.00;
			for (Object object : risultato) {
				Object[] oRiga = (Object[])object;
				totalInvoicedE += General.doubleZeroNull( (Double)oRiga[3] );
				paidInvoicesE += General.doubleZeroNull( (Double)oRiga[7]);
				Date payDt = (Date)oRiga[6];
				if (payDt==null){
					expiredInvoicesE += General.doubleZeroNull( (Double)oRiga[3] );
				}
				
			}
			grandTotalDueE = paidInvoicesE - totalInvoicedE;
			dbTotalInvoicedE.setValue(totalInvoicedE);
			dbPaidInvoicesE.setValue(paidInvoicesE);
			dbExpiredInvoicesE.setValue(expiredInvoicesE);
			dbGrandTotalDueE.setValue(grandTotalDueE);
			
			ListModelList listModelListCustEUR = new ListModelList();
			listModelListCustEUR.addAll(risultato);
			boxCustEUR.setModel(listModelListCustEUR);
			boxCustEUR.setItemRenderer(new CustEURRenderer() );
			
			
			//new General().MsgBox("Fine Procedura!", "NFYS");
			btnPreviewStatement.setDisabled(false);
			
			em.close();
		}
		
	}
	
	
	
	private class SupplierRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Supplier supplier = (Supplier)data;
			new Listcell(supplier.getCompanyname()).setParent(item);
			new Listcell(""+supplier.getSupplid()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}
	
	private class BoatNameRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Anayacht yacht = (Anayacht)data;
			new Listcell(yacht.getName()).setParent(item);
			new Listcell(""+yacht.getId()).setParent(item);
			new Listcell(yacht.getCorporation()).setParent(item);
			item.setAttribute("rigaBoatName", data);
		}
	}
	
	private class BrokerRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Broker broker = (Broker)data;
			new Listcell(broker.getDesc()).setParent(item);
			item.setAttribute("rigaBroker", data);
		}
	}
	
	
	private class CorporationRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Corporation corporation = (Corporation)data;
			new Listcell(corporation.getCorpname()).setParent(item);
			item.setAttribute("rigaCorporation", data);
		}
	}
	
	
	private class CustUSDRenderer implements ListitemRenderer {

		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
/*			
			  order_ integer DEFAULT 0,
			  custnuminvoice integer DEFAULT 0,
			  curr character varying(5),
			  totaltaxedvat double precision DEFAULT 0,
			  invoicedt timestamp without time zone,
			  duedate timestamp without time zone,
			  paydt timestamp without time zone,
			  paidamount double precision DEFAULT 0,
			  custid integer DEFAULT 0,
			  custname character varying(35)
*/
			
			
			Object[] object = (Object[])data;
			Integer order = (Integer)object[0];
			
			Integer invoiceNumber = null;
			String sinvoiceNumber = null;
			
			if (customersCard){
				invoiceNumber = (Integer)object[1];
			} else {
				sinvoiceNumber = (String)object[1];
			}
			String currency = (String)object[2];
			Double totalInvoice = (Double)object[3];
			Date invoiceDt = (Date)object[4];
			Date dueDate =  (Date)object[5];
			Date payDt = (Date)object[6];
			Double paidAmount = (Double)object[7];
			Double balance = General.doubleZeroNull(paidAmount)-General.doubleZeroNull(totalInvoice);
			String custName = (String)object[9];
			
			new Listcell(""+order).setParent(item);
			
			
			Textbox tbCustnuminvoice = new Textbox( ""+(customersCard?invoiceNumber:sinvoiceNumber));
			tbCustnuminvoice.setReadonly(true);
			tbCustnuminvoice.setCols(10);
			if ( (customersCard && invoiceNumber!=null && invoiceNumber!=0) || (!customersCard && sinvoiceNumber!=null && !sinvoiceNumber.isEmpty() ) ){
				tbCustnuminvoice.setStyle("color: blue; background: yellow; text-align: right;");
				
				tbCustnuminvoice.addEventListener("onClick", new EventListener() {
					public void onEvent(Event event) {
						Component componente = event.getTarget();
						
						if (clicked){
							return;
						}
						clicked = true;
									
					
						Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
						Object oRiga = boxCustUSD.getItemAtIndex(iIndex).getAttribute("rigaCustUSD");
						
						if (customersCard){
						
							Object[] object = (Object[])oRiga;
							Integer order = (Integer)object[0];
							Integer invoiceNumber = (Integer)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Custinvoice[] listInvoices = new CustinvoiceController().get(order, idCustomer);
							Custinvoice ci = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Custinvoice custinvoice = listInvoices[i];
								if (custinvoice.getCustnuminvoice().equals(invoiceNumber)){
									ci = custinvoice;
									break;
								}
							}
							
							if (ci==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
	
							map.put("ci", ci);
							map.put("si", null );
							map.put("seleziona", false);
							map.put("valore", 1);
								
							Window finestraInvoices = (Window) Executions.createComponents("/invoices/invoices.zul", null, map);
							finestraInvoices.doModal();
						} else {
							Object[] object = (Object[])oRiga;
							Integer order = (Integer)object[0];
							String invoiceNumber = (String)object[1];
							Integer idSupplier = (Integer)object[8];
							
							Suppinvoice[] listInvoices = new SuppinvoiceController().get(order, idSupplier);
							Suppinvoice si = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Suppinvoice suppinvoice = listInvoices[i];
								if (suppinvoice.getSuppnuminvoice().equals(invoiceNumber)){
									si = suppinvoice;
									break;
								}
							}
							
							if (si==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
	
							map.put("ci", null);
							map.put("si", si );
							map.put("seleziona", false);
							map.put("valore", 5);
								
							Window finestraInvoices = (Window) Executions.createComponents("/invoices/invoices.zul", null, map);
							finestraInvoices.doModal();							
						}
						
						clicked = false;

					}
					});
				
			}
			Listcell lcNumInvoice = new Listcell();
			lcNumInvoice.appendChild(tbCustnuminvoice);
			lcNumInvoice.setParent(item);

			
			//new Listcell(""+invoiceNumber).setParent(item);
			
			Listcell lc = new Listcell();
			Label lbl = new Label(""+currency);
			lbl.setStyle("color: green");
			lc.appendChild(lbl);
			lc.setParent(item);
			
			/*
			Listcell lc = new Listcell();
			Doublebox db = new Doublebox();
			db.setValue(totalInvoice);
			db.setFormat("###,##0.00");
			db.setStyle("align: right;");
			lc.appendChild(db);
			lc.setParent(item);
			*/
			
			new Listcell(""+General.decimalFormat("###,##0.00", totalInvoice)).setParent(item);
			new Listcell(""+General.formatoFecha(invoiceDt)).setParent(item);
			new Listcell(""+General.formatoFecha(dueDate)).setParent(item);
			new Listcell(""+General.formatoFecha(payDt)).setParent(item);
			
			
			Textbox tbPaidAmount = new Textbox( ""+General.decimalFormat("###,##0.00", General.doubleZeroNull(paidAmount) ) );
			tbPaidAmount.setReadonly(true);
			tbPaidAmount.setCols(14);
			tbPaidAmount.setStyle("color: blue; background: yellow; text-align: right;");
			if ( paidAmount!=null && !paidAmount.equals(0.00) ){

				
				tbPaidAmount.addEventListener("onClick", new EventListener() {
					public void onEvent(Event event) {
						Component componente = event.getTarget();
						
						if (clicked){
							return;
						}
						clicked = true;
						
						Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
						Object oRiga = boxCustUSD.getItemAtIndex(iIndex).getAttribute("rigaCustUSD");
						
						Object[] object = (Object[])oRiga;
						
						if (customersCard){
						
							Integer order = (Integer)object[0];
							Integer invoiceNumber = (Integer)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Custinvoice[] listInvoices = new CustinvoiceController().get(order, idCustomer);
							Custinvoice ci = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Custinvoice custinvoice = listInvoices[i];
								if (custinvoice.getCustnuminvoice().equals(invoiceNumber)){
									ci = custinvoice;
									break;
								}
							}
							
							if (ci==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
								
							String docType = "";
							String ref = "";
							String invref = "";
							Integer idInvoiceRecNum = 0;
	
							docType = "A";
							ref = ""+ci.getOrder();
							invref = ""+ci.getCustnuminvoice();
							idInvoiceRecNum = ci.getRecnum();
							if (ci.getType().equalsIgnoreCase("C") || ci.getType().equalsIgnoreCase("D") ){
								docType = "C";		
							}
								
							map.put("docType", docType);
							map.put("ref", ref);
							map.put("invref", invref);
							map.put("idInvoiceRecNum", idInvoiceRecNum); 
							map.put("valoreOpzioneMenu", 1 );
							map.put("ci", ci);
							map.put("si", (new Suppinvoice()) );
								
							Window finestraEditCash = (Window) Executions.createComponents("/editCash.zul", null, map);
							finestraEditCash.doModal();
						} else {
							Integer order = (Integer)object[0];
							String invoiceNumber = (String)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Suppinvoice[] listInvoices = new SuppinvoiceController().get(order, idCustomer);
							Suppinvoice si = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Suppinvoice suppinvoice = listInvoices[i];
								if (suppinvoice.getSuppnuminvoice().equals(invoiceNumber)){
									si = suppinvoice;
									break;
								}
							}
							
							if (si==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
								
							String docType = "";
							String ref = "";
							String invref = "";
							Integer idInvoiceRecNum = 0;
	
							docType = "P";
							ref = ""+si.getOrder();
							invref = ""+si.getSuppnuminvoice();
							idInvoiceRecNum = si.getRecnum();
							if (si.getType().equalsIgnoreCase("C") || si.getType().equalsIgnoreCase("D") ){
								docType = "D";		
							}
								
							map.put("docType", docType);
							map.put("ref", ref);
							map.put("invref", invref);
							map.put("idInvoiceRecNum", idInvoiceRecNum); 
							map.put("valoreOpzioneMenu", 5 );
							map.put("ci", null);
							map.put("si", si );
								
							Window finestraEditCash = (Window) Executions.createComponents("/editCash.zul", null, map);
							finestraEditCash.doModal();							
						}
						
						clicked = false;

					}
					});
				
			}
			
			lc = new Listcell();
			lc.appendChild(tbPaidAmount);
			lc.setParent(item);
			
			//new Listcell(""+General.decimalFormat("###,##0.00", paidAmount)).setParent(item);
			
			
			
			new Listcell(""+General.decimalFormat("###,##0.00", balance)).setParent(item);
			new Listcell(""+custName).setParent(item);
			
			item.setAttribute("rigaCustUSD", data);
		}
	}
	
	
	private class CustEURRenderer implements ListitemRenderer {

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {	
			
			Object[] object = (Object[])data;
			Integer order = (Integer)object[0];
			
			Integer invoiceNumber = null;
			String sinvoiceNumber = null;
			if (customersCard){
				invoiceNumber = (Integer)object[1];
			} else {
				sinvoiceNumber = (String)object[1];
			}
			
			String currency = (String)object[2];
			Double totalInvoice = (Double)object[3];
			Date invoiceDt = (Date)object[4];
			Date dueDate =  (Date)object[5]; 
			Date payDt = (Date)object[6];
			Double paidAmount = (Double)object[7];
			Double balance = General.doubleZeroNull(paidAmount)-General.doubleZeroNull(totalInvoice);
			String custName = (String)object[9];
			
			new Listcell(""+order).setParent(item);
			
			Textbox tbCustnuminvoice = new Textbox( ""+(customersCard?invoiceNumber:sinvoiceNumber));

			tbCustnuminvoice.setReadonly(true);
			tbCustnuminvoice.setCols(10);
			tbCustnuminvoice.setStyle("color: blue; background: yellow; text-align: right;");
			if ( (customersCard && invoiceNumber!=null && invoiceNumber!=0) || (!customersCard && sinvoiceNumber!=null && !sinvoiceNumber.isEmpty() ) ){
				
				tbCustnuminvoice.addEventListener("onClick", new EventListener() {
					public void onEvent(Event event) {
						Component componente = event.getTarget();
						
						if (clicked){
							return;
						}
						clicked = true;
						
						Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
						Object oRiga = boxCustEUR.getItemAtIndex(iIndex).getAttribute("rigaCustEUR");
						
						Object[] object = (Object[])oRiga;
						
						if (customersCard){
							Integer order = (Integer)object[0];
							Integer invoiceNumber = (Integer)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Custinvoice[] listInvoices = new CustinvoiceController().get(order, idCustomer);
							Custinvoice ci = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Custinvoice custinvoice = listInvoices[i];
								if (custinvoice.getCustnuminvoice().equals(invoiceNumber)){
									ci = custinvoice;
									break;
								}
							}
							
							if (ci==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
	
							map.put("ci", ci);
							map.put("si", null );
							map.put("seleziona", false);
							map.put("valore", 1);
								
							Window finestraInvoices = (Window) Executions.createComponents("/invoices/invoices.zul", null, map);
							finestraInvoices.doModal();
						} else {
							Integer order = (Integer)object[0];
							String invoiceNumber = (String)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Suppinvoice[] listInvoices = new SuppinvoiceController().get(order, idCustomer);
							Suppinvoice si = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Suppinvoice suppinvoice = listInvoices[i];
								if (suppinvoice.getSuppnuminvoice().equals(invoiceNumber)){
									si = suppinvoice;
									break;
								}
							}
							
							if (si==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
	
							map.put("ci", null);
							map.put("si", si );
							map.put("seleziona", false);
							map.put("valore", 5);
								
							Window finestraInvoices = (Window) Executions.createComponents("/invoices/invoices.zul", null, map);
							finestraInvoices.doModal();
							
						}
						
						
						
						clicked = false;

					}
					});
				
			}
			Listcell lcNumInvoice = new Listcell();
			lcNumInvoice.appendChild(tbCustnuminvoice);
			lcNumInvoice.setParent(item);
			//new Listcell(""+invoiceNumber).setParent(item);
			
			Listcell lc = new Listcell();
			Label lbl = new Label(""+currency);
			lbl.setStyle("color: orange");
			lc.appendChild(lbl);
			lc.setParent(item);
			
			new Listcell(""+General.decimalFormat("###,##0.00", totalInvoice)).setParent(item);
			new Listcell(""+General.formatoFecha(invoiceDt)).setParent(item);
			new Listcell(""+General.formatoFecha(dueDate)).setParent(item);
			new Listcell(""+General.formatoFecha(payDt)).setParent(item);
			
			
			Textbox tbPaidAmount = new Textbox( ""+General.decimalFormat("###,##0.00", General.doubleZeroNull( paidAmount) ) );
			tbPaidAmount.setReadonly(true);
			tbPaidAmount.setCols(14);
			if ( paidAmount!=null && !paidAmount.equals(0.00) ){
				tbPaidAmount.setStyle("color: blue; background: yellow; text-align: right;");
				
				tbPaidAmount.addEventListener("onClick", new EventListener() {
					public void onEvent(Event event) {
						Component componente = event.getTarget();
						
						if (clicked){
							return;
						}
						clicked = true;
						
						Integer iIndex = ((Listitem)componente.getParent().getParent()).getIndex();
						Object oRiga = boxCustEUR.getItemAtIndex(iIndex).getAttribute("rigaCustEUR");
						
						Object[] object = (Object[])oRiga;
						
						if (customersCard){
						
							Integer order = (Integer)object[0];
							Integer invoiceNumber = (Integer)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Custinvoice[] listInvoices = new CustinvoiceController().get(order, idCustomer);
							Custinvoice ci = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Custinvoice custinvoice = listInvoices[i];
								if (custinvoice.getCustnuminvoice().equals(invoiceNumber)){
									ci = custinvoice;
									break;
								}
							}
							
							if (ci==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
								
							String docType = "";
							String ref = "";
							String invref = "";
							Integer idInvoiceRecNum = 0;
	
							docType = "A";
							ref = ""+ci.getOrder();
							invref = ""+ci.getCustnuminvoice();
							idInvoiceRecNum = ci.getRecnum();
							if (ci.getType().equalsIgnoreCase("C") || ci.getType().equalsIgnoreCase("D") ){
								docType = "C";		
							}
								
							map.put("docType", docType);
							map.put("ref", ref);
							map.put("invref", invref);
							map.put("idInvoiceRecNum", idInvoiceRecNum); 
							map.put("valoreOpzioneMenu", 1 );
							map.put("ci", ci);
							map.put("si", (new Suppinvoice()) );
								
							Window finestraEditCash = (Window) Executions.createComponents("/editCash.zul", null, map);
							finestraEditCash.doModal();
						} else {
							Integer order = (Integer)object[0];
							String invoiceNumber = (String)object[1];
							Integer idCustomer = (Integer)object[8];
							
							Suppinvoice[] listInvoices = new SuppinvoiceController().get(order, idCustomer);
							Suppinvoice si = null;
							for (int i = 0; i < listInvoices.length; i++) {
								Suppinvoice suppinvoice = listInvoices[i];
								if (suppinvoice.getSuppnuminvoice().equals(invoiceNumber)){
									si = suppinvoice;
									break;
								}
							}
							
							if (si==null){
								clicked = false;
								return;
							}
							
							HashMap map = new HashMap();
							map.put("lNuovo", true);
								
							String docType = "";
							String ref = "";
							String invref = "";
							Integer idInvoiceRecNum = 0;
	
							docType = "P";
							ref = ""+si.getOrder();
							invref = ""+si.getSuppnuminvoice();
							idInvoiceRecNum = si.getRecnum();
							if (si.getType().equalsIgnoreCase("C") || si.getType().equalsIgnoreCase("D") ){
								docType = "D";		
							}
								
							map.put("docType", docType);
							map.put("ref", ref);
							map.put("invref", invref);
							map.put("idInvoiceRecNum", idInvoiceRecNum); 
							map.put("valoreOpzioneMenu", 5 );
							map.put("ci", null);
							map.put("si", si );
								
							Window finestraEditCash = (Window) Executions.createComponents("/editCash.zul", null, map);
							finestraEditCash.doModal();
						}
						
						clicked = false;

					}
					});
				
			}
			
			lc = new Listcell();
			lc.appendChild(tbPaidAmount);
			lc.setParent(item);
			
			//new Listcell(""+General.decimalFormat("###,##0.00", paidAmount)).setParent(item);
			
			
			new Listcell(""+General.decimalFormat("###,##0.00", balance)).setParent(item);
			new Listcell(""+custName).setParent(item);
			
			item.setAttribute("rigaCustEUR", data);
		}
	}
	
}
